|
Polymorphism is a means to uniformly handle objects of classes related by inheritance. It allows to send a message to an object without having to know at compile time about the exact class of the receiver. Hence, binding of a message to an implementation of a message has to take place at run time (dynamic binding). Assume you instantiate a car object like this (informal:
This means my_car is either a car, an e-car, or a gas-car. In particular, this instantiation allows to change the type of my_car during its lifetime (e.g. from e-car to gas-car). Such objects are called polymorphic. If later on a method of my_car is invoked, the runtime system decides which implementation of the method has to be chosen because each version of the car may implement the method differently. |
Example: Assume my_car is currently an e-car.
The slow_down method of e-car will be executed.
This will produce a runtime error because my_car is currently an e-car. E-car has no display_fuel_status method. But remember that the type of my_car can change during runtime. If the type changes to gas-car this method invocation will work. The occurrence of runtime errors is one of the potential problems if polymorphism is applied. Such errors can be avoided if an OO language makes certain restrictions, e.g. forbid the invocation of display_fuel_status with my_Car because some cars do not have this method. |